package cn.neusoft.controller;

import cn.neusoft.domain.CargoDeployBill;
import cn.neusoft.domain.CargoDescription;
import cn.neusoft.domain.CargoDistributeBill;
import cn.neusoft.domain.DeployBillStageEnum;
import cn.neusoft.service.CargoAndDescriptionService;
import cn.neusoft.service.DisBillService;
import cn.neusoft.tool.PageSet;
import cn.neusoft.vo.ResultBean;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/disBill")
public class DisBillController {

    @Autowired
    private DisBillService disBillService;
    @Autowired
    private CargoAndDescriptionService cargoAndDescriptionService;
    @PostMapping("/changeDisBill")
    public synchronized ResultBean changeDisBill(@RequestBody Map<String, Object> map){
      ResultBean resultBean;

      if(map != null){
        try{
            int id = (int) map.get("id");
            CargoDistributeBill find = disBillService.getDisBillByID(id);
            if(find != null){
                String warehouseName = (String) map.get("warehouseName");
                String operator = (String) map.get("operator");
                String notes = (String) map.get("notes");
                String distributer = (String) map.get("distributer");
                String recipient = (String) map.get("recipient");
                java.sql.Date date = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse((String) map.get("date")).getTime());

                List<Map<String, String>> list = (List<Map<String, String>>) (map.get("cargoInf"));
                String stage = (String) map.get("stage");
                Map<String, Double> cargoInf = new HashMap<>();
                for(Map<String, String> m : list){
                    cargoInf.put(m.get("cargoName"), Double.valueOf(m.get("quantities")));
                }
                find.setCargosInf(cargoInf);
                find.setWarehouseName(warehouseName);
                find.setOperator(operator);
                find.setNotes(notes);
                find.setDistributer(distributer);
                find.setRecipient(recipient);
                find.setDate(date);
                find.setStage(stage);

                int reply = disBillService.changeDisBill(find);
                switch(reply){
                    case 1:
                        resultBean = ResultBean.success();
                        break;
                    case 0:
                        resultBean = ResultBean.error(7051, "失败");
                        break;
                    default:
                        resultBean = ResultBean.error(7052, "未知错误");
                        break;
                }
            }
            else{
                resultBean = ResultBean.error(7052, "未知错误");

            }

        }catch (Exception e){
          e.printStackTrace();
          resultBean = ResultBean.error(1, "错误");
        }


      }
      else{
        resultBean = ResultBean.error(7050, "输入为空");
      }

      return resultBean;
    }
    @PostMapping("/queryAllDisBill")

    public synchronized ResultBean queryAllDisBill(){
        ResultBean resultBean = null;

        resultBean = ResultBean.success(disBillService.queryAllDisBill());

        return resultBean;
    }

    @PostMapping("/generateDisBill")
    @ApiOperation("生成存储分发单")
    public synchronized ResultBean generateDisBill(@RequestBody Map<String, Object> map){
        ResultBean resultBean;

        if(map != null){
            try{
              String warehouseName = (String) map.get("warehouseName");
              String operator = (String) map.get("operator");
              String notes = (String) map.get("notes");
              String distributer = (String) map.get("distributer");
              String recipient = (String) map.get("recipient");
                java.sql.Date date = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse((String) map.get("date")).getTime());

              List<Map<String, String>> list = (List<Map<String, String>>) (map.get("cargoInf"));
              String stage = (String) map.get("stage");
              Map<String, Double> cargoInf = new HashMap<>();
              for(Map<String, String> m : list){
                cargoInf.put(m.get("cargoName"), Double.valueOf(m.get("quantities")));
              }

              CargoDistributeBill cargoDistributeBill = new CargoDistributeBill(cargoInf, warehouseName, operator, notes,
                distributer, recipient, date, stage);
              int reply = disBillService.generateDisBill(cargoDistributeBill);
              switch(reply){
                case 1:
                  resultBean = ResultBean.success();
                  break;
                case 0:
                  resultBean = ResultBean.error(7051, "失败");
                  break;
                default:
                  resultBean = ResultBean.error(7052, "未知错误");
                  break;
              }
            }catch (Exception e){
              e.printStackTrace();
              resultBean = ResultBean.error(1, "错误");
            }


        }
        else{
            resultBean = ResultBean.error(7050, "输入为空");
        }

        return resultBean;
    }
    @GetMapping("/deleteDisBill/{id}")
    public synchronized ResultBean deleteDisBill(@PathVariable int id){
        ResultBean resultBean = null;

        switch(disBillService.deleteDisBill(id)){
            case 1:
                resultBean = ResultBean.success();
                break;
            default:
                resultBean = ResultBean.error(7058, "错误");
        }



        resultBean = ResultBean.success();
        return resultBean;
    }
    @PostMapping("/getAllDisPage")

    public synchronized ResultBean getAllDisPage(@RequestBody Map<String, String> map){
        ResultBean resultBean;

        List<CargoDisBillReturn> ans = new ArrayList<CargoDisBillReturn>();


        try{
            int pageNum = Integer.parseInt(map.get("pageNum"));
            int pageSize = Integer.parseInt(map.get("pageSize"));
            Date date =  null;
            if(!map.get("date").equals("")){
                date = new SimpleDateFormat("yyyy-MM-dd").parse(map.get("date"));
            }

            String warehouseName = map.get("warehouseName");
            String cargoName = map.get("cargoName");

            List<CargoDistributeBill> list = disBillService.queryAllDisBill();

            for(CargoDistributeBill c : list){
                double cargoTotal = 0;
                double totalPrice = 0;
                if(!warehouseName.equals("") && !c.getWarehouseName().equals(warehouseName)){
                    continue;
                }
                if(!(date == null) && !c.getDate().equals(date)){
                    continue;
                }
                List<DisTableElement> line = new ArrayList<>();
                boolean isHad = false;
                System.out.println(c.getCargosInf() + "?");
                for(Map.Entry<String, Double> entry : c.getCargosInf().entrySet()){
                    if(cargoName.equals("") || entry.getKey().equals(cargoName)){
                        isHad = true;
                    }
                    DisTableElement disTableElement = null;
                    CargoDescription cargoDescription = cargoAndDescriptionService.getByDesName(entry.getKey());
                    if(cargoDescription != null){
                        disTableElement = new DisTableElement(entry.getKey(), Double.toString(entry.getValue()), Double.toString(cargoDescription.getSalePrice()),
                                Integer.toString(cargoDescription.getId()), cargoDescription.getManufacture());
                        totalPrice += cargoDescription.getSalePrice();
                    }
                    else{
                        disTableElement = new DisTableElement(entry.getKey(), Double.toString(entry.getValue()), "未设置商品", "未设置商品", "未设置商品");
                    }

                    cargoTotal += entry.getValue();
                    line.add(disTableElement);
                }
                if(isHad){
                    CargoDisBillReturn cargoDisBillReturn = new CargoDisBillReturn(c.getId(), c.getWarehouseName(), c.getOperator(),
                            c.getNotes(), cargoTotal, totalPrice, c.getDistributer(), c.getRecipient(), c.getDate(), line);
                    ans.add(cargoDisBillReturn);
                }
            }


            PageSet<CargoDisBillReturn> pageSet = new PageSet<CargoDisBillReturn>(ans, pageSize);
            Map<String, Object> answer = new HashMap<>();
            answer.put("total", pageSet.getTotal());
            answer.put("list", pageSet.getPage(pageNum));

            resultBean = ResultBean.success(answer);

        }catch(Exception e){
            e.printStackTrace();
            resultBean = ResultBean.error(1, "错误");
        }

        return resultBean;
    }

    private class DisTableElement {
        private String cargoName;
        private String quantities;
        private String price;
        private String id;
        private String manufacture;

        public DisTableElement(String cargoName, String quantities, String price, String id, String manufacture) {
            this.cargoName = cargoName;
            this.quantities = quantities;
            this.price = price;
            this.id = id;
            this.manufacture = manufacture;
        }

        public String getCargoName() {
            return cargoName;
        }

        public void setCargoName(String cargoName) {
            this.cargoName = cargoName;
        }

        public String getQuantities() {
            return quantities;
        }

        public void setQuantities(String quantities) {
            this.quantities = quantities;
        }

        public String getPrice() {
            return price;
        }

        public void setPrice(String price) {
            this.price = price;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getManufacture() {
            return manufacture;
        }

        public void setManufacture(String manufacture) {
            this.manufacture = manufacture;
        }
    }

    private class CargoDisBillReturn {
        private int id;
        private String warehouseName;
        private String operator;
        private String notes;

        private double cargoTotal;
        private double totalPrice;
        private String distributer;
        private String recipient;
        private java.sql.Date date;
        private List<DisTableElement> list;

        public CargoDisBillReturn(int id, String warehouseName, String operator, String notes, double cargoTotal, double totalPrice, String distributer, String recipient, java.sql.Date date, List<DisTableElement> list) {
            this.id = id;
            this.warehouseName = warehouseName;
            this.operator = operator;
            this.notes = notes;
            this.cargoTotal = cargoTotal;
            this.totalPrice = totalPrice;
            this.distributer = distributer;
            this.recipient = recipient;
            this.date = date;
            this.list = list;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getWarehouseName() {
            return warehouseName;
        }

        public void setWarehouseName(String warehouseName) {
            this.warehouseName = warehouseName;
        }

        public String getOperator() {
            return operator;
        }

        public void setOperator(String operator) {
            this.operator = operator;
        }

        public String getNotes() {
            return notes;
        }

        public void setNotes(String notes) {
            this.notes = notes;
        }

        public double getCargoTotal() {
            return cargoTotal;
        }

        public void setCargoTotal(double cargoTotal) {
            this.cargoTotal = cargoTotal;
        }

        public double getTotalPrice() {
            return totalPrice;
        }

        public void setTotalPrice(double totalPrice) {
            this.totalPrice = totalPrice;
        }

        public String getDistributer() {
            return distributer;
        }

        public void setDistributer(String distributer) {
            this.distributer = distributer;
        }

        public String getRecipient() {
            return recipient;
        }

        public void setRecipient(String recipient) {
            this.recipient = recipient;
        }

        public java.sql.Date getDate() {
            return date;
        }

        public void setDate(java.sql.Date date) {
            this.date = date;
        }

        public List<DisTableElement> getList() {
            return list;
        }

        public void setList(List<DisTableElement> list) {
            this.list = list;
        }

    }

}
